import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeUtility;
import javax.mail.search.AndTerm;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SentDateTerm;
import javax.mail.search.SubjectTerm;

import org.json.simple.JSONValue;

import model.UserInfo;


public class AddUserInfoMgr extends Thread
{
    private static final String EMAIL = "junheifcyd@163.com";
    private static final String PWD = "lovegq";
    private final static String CONFIRM_SUBJECT = "你的預訂申請已被確認";
    private Map<String, UserInfo> itemMap = new HashMap<String, UserInfo>();
    private boolean isRun = true;
    private static final long sleepTime = 5 * 60 * 1000;
    public enum EmailType
    {
        ADDED, ERROR, UPDATED, REMOVED
    }
    public void run()
    {
        while (isRun)
        {
            try
            {
                checkEmail();
                sleep(sleepTime);
            }
            catch (InterruptedException e)
            {
            }
        }
    }
    
    @SuppressWarnings("unchecked")
    private void checkEmail()
    {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props);
        try
        {
            Store store = session.getStore("pop3");
            store.connect("pop3.163.com", EMAIL, PWD);
            Folder folder = store.getFolder("Inbox");
            folder.open(Folder.READ_ONLY);
            
            Calendar c = Calendar.getInstance();
            SentDateTerm endDateTerm = new SentDateTerm(ComparisonTerm.GE, c.getTime());
            c.add(Calendar.HOUR, -24);
            SentDateTerm startDateTerm = new SentDateTerm(ComparisonTerm.LT, c.getTime());
            SearchTerm dateTerm = new AndTerm(startDateTerm, endDateTerm);
            
            SearchTerm subjectTerm = new SubjectTerm(CONFIRM_SUBJECT);
            Message[] messages = folder.search(new AndTerm(dateTerm, subjectTerm));
            for (int i = 0; i < messages.length; i++)
            {
                Message mes = messages[i];
                String subject = getSubject(mes);
                Map<String, String> userInfoMap = (Map<String, String>) JSONValue.parse(subject);
                
                UserInfo bookItem = new UserInfo();
                String governmentId = userInfoMap.get(UserInfo.GOVERNMENT_ID);
                bookItem.setGovernmentId(governmentId);
                bookItem.setFirstName(userInfoMap.get(UserInfo.FIRST_NAME));
                bookItem.setLastName(userInfoMap.get(UserInfo.LAST_NAME));
                bookItem.setSku(userInfoMap.get(UserInfo.SKU_ID));
//                bookItem.setForwardEmail(mes.getFrom()[0]);
                if (!bookItem.isValid())
                {
                    if (governmentId != null && !"".equals(governmentId))
                    {
                        itemMap.remove(governmentId);
                        sendEmail(bookItem, EmailType.REMOVED);
                    }
                    else
                    {
                        sendEmail(bookItem, EmailType.ERROR);
                    }
                    return;
                }
                boolean isAdded = userInfoMap.get(governmentId) != null;
                itemMap.put(governmentId, bookItem);
                sendEmail(bookItem, isAdded ? EmailType.ADDED : EmailType.UPDATED);
            }
            folder.close(false);
            store.close();
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }
    
    private void sendEmail(UserInfo item, EmailType type)
    {
        
    }
    
    private String getSubject(Message message)
    {
        try
        {
            return MimeUtility.decodeText(message.getSubject());
        }
        catch (UnsupportedEncodingException e)
        {
        }
        catch (MessagingException e)
        {
        }
        return "";
    }
}
